package com.klod.news.page.home


import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Notifications
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ScrollableTabRow
import androidx.compose.material3.SearchBar
import androidx.compose.material3.SearchBarDefaults
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRowDefaults.tabIndicatorOffset
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.zIndex
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import com.klod.news.R
import com.klod.news.data.bean.NewsDetailBean
import com.klod.news.ext.parseState
import com.klod.news.ext.showToast
import com.klod.news.page.home.content.OtherNews
import com.klod.news.page.home.content.RecommendNews
import com.klod.news.page.news.NewsList
import com.klod.news.viewmodel.MainActivityVm
import com.klod.news.widget.BannerView
import com.klod.news.widget.MyCapsuleBackgroundIndicator
import org.koin.androidx.compose.koinViewModel


@Composable
fun HomePage(
    mainAcVm: MainActivityVm = koinViewModel(),
    backgroundModifier: Modifier = Modifier
) {

    var getAllNews  =mainAcVm.newsList.collectAsLazyPagingItems()
    Column(modifier = Modifier.windowInsetsPadding(WindowInsets.statusBars)) {
        //顶部搜索
        HomePageTopBar()
        //内容
        HomePageContent(newsList = getAllNews)

    }


}

/**
 * 首页内容
 */
@Composable
fun HomePageContent(mainAcVm: MainActivityVm= koinViewModel(),
                   newsList: LazyPagingItems<NewsDetailBean>
) {


    mainAcVm.bannerData.collectAsStateWithLifecycle(initialValue = null).value?.parseState(
        retry = {
            mainAcVm.getBannerData()
        },
        errorModifier = Modifier
            .height(192.dp),

        ) {
        onSuccess {
            //展示Banner
            BannerView(it) { item ->
                //点击Banner
                item.content.showToast()
            }
        }

    }

    Spacer(Modifier.height(8.dp))
    //TabLayout
    var selectedTabIndex by remember { mutableIntStateOf(0) }
    mainAcVm.newsTypeData.collectAsStateWithLifecycle(initialValue = null).value?.parseState(
        retry = { mainAcVm.getNewsTypeData() }
    ) {
        onSuccess {
            ScrollableTabRow(
                modifier = Modifier.fillMaxWidth(),
                edgePadding = 0.dp,
                selectedTabIndex = selectedTabIndex,
                divider = {},
                tabs = {
                    it.forEachIndexed { index, bean ->
                        val textStyle = if (selectedTabIndex == index) {
                            MaterialTheme.typography.bodyLarge
                        } else {
                            MaterialTheme.typography.labelMedium
                        }

                        Tab(
                            modifier = Modifier.zIndex(1f),
                            selected = selectedTabIndex == index,
                            onClick = {
                                selectedTabIndex = index
                                mainAcVm.tabSelect(bean)
                            },
                            selectedContentColor = Color.White,
                            unselectedContentColor = MaterialTheme.colorScheme.primary,
                            text = { Text(text = bean.name, style = textStyle) }
                        )
                    }
                },
                indicator = { tabPositions ->

                    MyCapsuleBackgroundIndicator(
                        modifier = Modifier.tabIndicatorOffset(tabPositions[selectedTabIndex]),
                        tabPositions = tabPositions,
                        selectedTabIndex = selectedTabIndex,
                        color = MaterialTheme.colorScheme.primary
                    )
                })
            //TabLayout内容
            mainAcVm.newsTypeSelect.collectAsStateWithLifecycle().apply {
                when (this.value.name) {
                    "推荐" -> RecommendNews()
//            "热门" -> HotNews()
                    else -> OtherNews()
                }
            }
        }


    }

//    val state  = remember { mutableIntStateOf(0) }
////    var getAllNews :  Flow<PagingData<NewsDetailBean>>? = null
//    LaunchedEffect(state) {
////        getAllNews = mainAcVm.newsList
//    }
    //列表
//    NewsList(modifier = Modifier, data = getAllNews?.collectAsLazyPagingItems()?:flowOf(PagingData.from(listOf(NewsDetailBean()))).collectAsLazyPagingItems())
    NewsList(modifier = Modifier.fillMaxWidth(), data = newsList,vm = mainAcVm)
}


/**
 * 首页顶部布局
 * Logo 搜索 通知 头像
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HomePageTopBar() {

    var query by remember { mutableStateOf("") }
    var expanded by remember { mutableStateOf(false) }
    Row(
        verticalAlignment = Alignment.CenterVertically,

        ) {
        AnimatedVisibility(!expanded) {

            Row {
                Spacer(modifier = Modifier.width(8.dp))
                Image(
                    painter = painterResource(id = R.mipmap.news_app_logo),
                    contentDescription = "Logo图标",
                    modifier = Modifier
                        .size(35.dp)
                        .clip(CircleShape.copy())

                )
                Spacer(modifier = Modifier.width(8.dp))
            }
        }
        SearchBar(
            modifier = Modifier
                .weight(1f),

            inputField = {
                SearchBarDefaults.InputField(
                    query = query,
                    onQueryChange = { query = it },
                    onSearch = { expanded = false },
                    expanded = expanded,

                    onExpandedChange = { expanded = it },
                    placeholder = { Text("Search", color = MaterialTheme.colorScheme.primary) },
                    leadingIcon = {
                        if (expanded) {
                            IconButton(onClick = { expanded = false }) {
                                Icon(
                                    Icons.AutoMirrored.Filled.ArrowBack,
                                    contentDescription = "Back",
                                    tint = MaterialTheme.colorScheme.primary
                                )
                            }
                        } else {
                            Icon(
                                Icons.Filled.Search, contentDescription = "Search",
                                tint = MaterialTheme.colorScheme.primary
                            )
                        }
                    },
                    trailingIcon = {
                        if (query.isNotEmpty()) {
                            IconButton(onClick = { query = "" }) {
                                Icon(
                                    Icons.Filled.Close, contentDescription = "Close",
                                    tint = MaterialTheme.colorScheme.primary
                                )
                            }
                        }
                    },

                    )
            },
            colors = SearchBarDefaults.colors(
                containerColor = MaterialTheme.colorScheme.primaryContainer,
                dividerColor = MaterialTheme.colorScheme.onPrimaryContainer
            ),
            expanded = expanded,
            onExpandedChange = { expanded = it },

            ) {
            AnimatedVisibility(visible = expanded) {

                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(12.dp)
                        .background(color = MaterialTheme.colorScheme.primaryContainer)
                ) {
                    Column {
                        // 这里放置搜索结果内容
                        Text(text = "搜索内容1", color = MaterialTheme.colorScheme.primary)
                        Text(text = "搜索内容1")
                        Text(text = "搜索内容1")
                        Text(text = "搜索内容1")
                        Text(text = "搜索内容1")
                    }

                }
            }
        }

        AnimatedVisibility(!expanded) {
            Spacer(modifier = Modifier.width(8.dp))
            Icon(
                Icons.Filled.Notifications,
                contentDescription = "通知消息",
                tint = MaterialTheme.colorScheme.primary,
                modifier = Modifier
                    .size(25.dp)
                    .clip(CircleShape.copy())

            )
            Spacer(modifier = Modifier.width(8.dp))
        }
        AnimatedVisibility(!expanded) {
            Row {
                Image(
                    painter = painterResource(id = R.mipmap.news_app_logo),
                    contentDescription = "头像",
                    modifier = Modifier
                        .size(39.dp)
                        .clip(CircleShape.copy())
                )
                Spacer(modifier = Modifier.width(8.dp))
            }


        }
    }


}